package com.example.test.controllers;

import com.example.test.dao.ActorRepository;
import com.example.test.dao.DirectorRepository;
import com.example.test.dao.MovieRepository;
import com.example.test.dao.RoleRepository;
import com.example.test.entities.Actor;
import com.example.test.entities.Director;
import com.example.test.entities.Movies;
import com.example.test.entities.Roles;
import com.example.test.services.DirectorService;
import com.example.test.services.MovieService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping("Movies")
public class MovieControllers {

    @Autowired
    MovieService movieService;
    @Autowired
    DirectorService directorService;
    @Autowired
    RoleRepository roleRepository;
    @Autowired
    ActorRepository actorRepository;

    @GetMapping("/new")
    public String displayMovieForm(Model model){

        Movies aMovie=new Movies();
        List<Roles> roles=roleRepository.findAll();
        List<Actor> actors=actorRepository.findAll();
        List<Director> directors=directorService.getAll();
        model.addAttribute("movie",aMovie);
        model.addAttribute("role",roles);
        model.addAttribute("actor",actors);
        model.addAttribute("direct",directors);
        return "new-movie";
    }

    @PostMapping("/save")
    public String creatMovie(Model model, @RequestParam List<Long> roles,@RequestParam List<Long> actors,@RequestParam List<Long> director, Movies movies ){
        movieService.save(movies);
        Iterable<Roles> choseRoles= roleRepository.findAllById(roles);
        for (Roles role : choseRoles){
            role.setMovies(movies);
            roleRepository.save(role);
        }

        return "redirect:/movies";
    }

}
